package com.websocket.controller;

import com.websocket.entity.Greeting;
import com.websocket.entity.HelloMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.util.HtmlUtils;

import java.nio.charset.Charset;

@Controller
public class GreetingController {

    /*---------------------会经过消息的代理----------------------------*/
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        System.out.println("接收到客户端传递的消息1：" + message.getName());
        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
    }

    //    @MessageMapping("/hello/{id}")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message,
                             @DestinationVariable("id") Integer id) throws Exception {
        System.out.println("接收到客户端传递的消息2：" + message.getName() + ", " + id);
        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
    }

    /*--------------------------直接发送给客户端-------------------------------*/
//    @MessageMapping("/hello/toClient")
    @SubscribeMapping("/topic/greetings") // 直接将消息发送给此注解订阅的相同的客户端
    public Greeting toClient(HelloMessage message) throws Exception {
        int i = 1 / 0;
        System.out.println("接收到客户端传递的消息3：" + message.getName());
        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
    }


    /*-----------------------未使用上面方法中的注解发送消息的方式---------------------------*/
    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/hello/toClient")
    public void templateSendMsg(HelloMessage message) {
        System.out.println("接收到客户端传递的消息4：" + message.getName());
        simpMessagingTemplate.convertAndSend("/topic/greetings", (HtmlUtils.htmlEscape(message.getName()) + "!").getBytes(Charset.defaultCharset()));
    }


    /**
     * 异常的方法抛出异常之后，会被此方法所捕获。
     *
     * @param exception
     * @return
     */
    @MessageExceptionHandler
    public RuntimeException handleException(RuntimeException exception) {
        return exception;
    }
}